package toy.keli.edic.ui.home.game.ext

import android.app.Activity
import android.content.Context.WINDOW_SERVICE
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Point
import android.os.Handler
import android.view.OrientationEventListener
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.Button
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import toy.keli.edic.R
import toy.keli.edic.data.DictionaryDatabase
import toy.keli.edic.data.adapter.StringsAdapter
import toy.keli.edic.ui.home.TTSListener
import toy.keli.edic.ui.main.extend.setTimeout
import toy.keli.edic.ui.navigation.NavScreen
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.util.FontManager
import toy.keli.edic.util.ScreenUtil
import toy.keli.edic.view.WordSearchView
import java.util.Locale
import java.util.Objects
import kotlin.math.abs


class LineGame  {

    var args by mutableStateOf( listOf<String>() )
    val names = mutableStateMapOf<String,String>()

    private var ttsListener: TTSListener? = null
    private var gameWords: ListView? = null
    var wordMap: MutableMap<String, String> = HashMap()
    var act = ActivityRun.context as Activity
    val words: String
        get() {
            val words = StringBuilder()
            for (arg in args) {
                if (!arg.isEmpty()) {
                    words.append(arg).append("\n")
                }
            }
            return words.toString()
        }
    /**
     * 添加分页机制
     */
    val pageWords = arrayListOf<List<String>>()
    val pageSize: Int  //页数
        get() {
            if(pageWords.size==0) {
                pageWords.addAll(args.chunked(10))
                args =pageWords[pageIndex]
            }
            return pageWords.size
        }
    var pageIndex:Int = 0  //修改分页
    lateinit var wordSearchView: WordSearchView

    constructor(words:List<String>){
        args=words;
        if(ttsListener==null) {
            val db: DictionaryDatabase = DictionaryDatabase.getDatabase(act)
            for (arg in args) {
                var zh: String = db.ch(arg)
                zh = zh.replace("^\\w+\\.".toRegex(), "")
                wordMap[arg] = zh
                names.put(arg,zh)
            }
            ttsListener = TTSListener(act) { null }
        }
    }
    fun pageIndex(i:Int){
        pageIndex = i
        if(pageWords.size>0)
        args = pageWords[i]
    }
    fun initView(view:View,i:Int) {
        pageIndex(i)
        view.apply {
            val tvStrikethrough = findViewById<TextView>(R.id.tv_strikethrough)
            if (tvStrikethrough == null) return
            val backBtn = findViewById<Button>(R.id.tv_back)
            backBtn?.setOnClickListener { v: View? -> finish() }
            tvStrikethrough.text = words
//            tvStrikethrough.paintFlags = tvStrikethrough.paintFlags // | Paint.STRIKE_THRU_TEXT_FLAG
//            tvStrikethrough.visibility = View.GONE

            wordSearchView = findViewById(R.id.wordsGrid)
            wordSearchView.setTypeface(FontManager.getTypeface(act, FontManager.POYNTER))

            for (arg in args) {
                wordSearchView.addWord(arg)
            }

            wordSearchView.show()
            wordSearchView.setOnWordSearchedListener { word ->
                var word = word
                word = wordSearchView.getWord(word).toLowerCase()

                //word=word.toLowerCase();
                for (i in args.indices) {
                    if (args[i] == word) {
                        gameWords!!.getChildAt(i).apply {
//                            visibility = View.GONE

//                            (this as TextView).text =
//                                (i + 1).toString() + ".  " + wordMap.get(word) + "   ---- " + word
                        }
//                        args[i] = ""
                    }
                }

                tvStrikethrough.text = words
                Toast.makeText(
                    act,
                    word.toString(),
                    Toast.LENGTH_SHORT
                ).show()
                ttsListener?.setLocale(Locale.ENGLISH)
                ttsListener?.speak(word)
                val finalWord: String = word
                Handler().postDelayed({
                    ttsListener?.setLocale(Locale.TAIWAN)
                    ttsListener?.speak(finalWord)
                }, 2000)
                if (words.isEmpty()) {
                    Handler()
                        .postDelayed({ onOver() }, 2000)
                }
                wordSearchView.changeDrawColor()
                names.put(word,word)
            }

            initWordsListView(tvStrikethrough.parent as ViewGroup, wordSearchView)
        }
    }

    private fun finish() {
        NavScreen.openHome(0)
    }

    fun initWordsListView(box: ViewGroup, wordsGrid: WordSearchView) {
        gameWords = ListView(act)
        val ws = arrayOfNulls<String>(args.size)
        var i = 0
        for (k in args) {
//            ws[i++] = k + " " + wordMap[k]
            if(wordMap[k]!=null && wordMap[k]?.length!! >0){
                ws[i++] = wordMap[k]
            }else {
                ws[i++] = k
            }
        }
        val gameAdapter: ListAdapter = object : StringsAdapter(ws, true) {
            override fun getView(i: Int, view: View?, viewGroup: ViewGroup?): View {
                val tv = super.getView(i, view, viewGroup) as TextView
                tv.setTextColor(act.resources.getColor(R.color.white))
                return tv
            }
        }
        gameWords!!.adapter = gameAdapter
        gameWords!!.post { setListViewAutoHeight(gameWords) }
        //项目的单击事件
        gameWords!!.onItemClickListener =
            OnItemClickListener { av: AdapterView<*>?, v: View?, index: Int, nuse: Long ->
                val arg = args[index]
                setTimeout(500,4){
                    wordsGrid.show(arg)
                }
            }
        box.removeViewAt(0)
        box.addView(gameWords)
    }

    /** 计算高度 https://www.cnblogs.com/Westfalen/p/5427402.html  */
    private fun setListViewAutoHeight(lv: ListView?) {
        if (lv == null || lv.count <= 0) return
        var totalHeight = 0
        for (i in 0 until lv.count) {
            val view = lv.adapter.getView(i, null, lv)
            view.measure(0, 0)
            totalHeight += view.measuredHeight
        }
        val params = lv.layoutParams
        params.height =
            totalHeight + lv.dividerHeight * (lv.count - 1) + lv.paddingTop + lv.paddingBottom
        lv.layoutParams = params
    }

    private fun onOver() {
        Toast.makeText(act, "You win!!!", Toast.LENGTH_SHORT).show()
        finish()
    }



}
